package com.dpiinc.TechPage.user;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.dpiinc.TechPage.BaseActivity;
import com.dpiinc.TechPage.LoginActivity;
import com.dpiinc.TechPage.MessageEvent;
import com.dpiinc.TechPage.R;
import com.dpiinc.TechPage.activity.BottomBarActivity;
import com.dpiinc.TechPage.api.BaseObserver;
import com.dpiinc.TechPage.api.RetrofitFactory;
import com.dpiinc.TechPage.api.RxSchedulers;
import com.dpiinc.TechPage.model.BaseEntity;
import com.dpiinc.TechPage.model.jbean.AuthenticateInfo;
import com.dpiinc.TechPage.room.RoomAiWriterDatabase;
import com.dpiinc.TechPage.room.bean.UserEntity;
import com.dpiinc.TechPage.user.logic.NoteLabelLogic;
import com.dpiinc.TechPage.user.utils.ToastUtils;
import com.dpiinc.TechPage.widget.LoadingView;
import com.dpiinc.TechPage.widget.VerifyCodeView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.Locale;

import androidx.annotation.Nullable;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;

/**
 * Created by hu489_000 on 2018-06-24.
 */

public class VerifyCodeActivity extends BaseActivity {
    private static final String TAG = "VerifyCodeActivity";
    TextView input_verify_code2;
    VerifyCodeView verify_code_view;
    Button btn_resend;
    String mTelPhone;
    String country_number;

    EventHandler eh = new EventHandler() {

        @Override
        public void afterEvent(int event, int result, Object data) {
//            Message msg = new Message();
//            msg.arg1 = event;
//            msg.arg2 = result;
//            msg.obj = data;
//            mHandler.sendMessage(msg);

            Log.d("huhu", "event=== " + event + "   result===" + result + "      data===" + data);

            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    //TODO 可以登录了
                    MessageEvent msg = new MessageEvent(MessageEvent.EVENT_USER_VERIFICATION_OK);
                    msg.setObject(mTelPhone);
                    EventBus.getDefault().post(msg);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    });
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    //倒计时开始
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startCountDownTimer();
                        }
                    });
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                }
            } else {
                ((Throwable) data).printStackTrace();
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码失败
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btn_resend.setText(R.string.resend);
                            btn_resend.setEnabled(true);
                            ToastUtils.showTopTip(VerifyCodeActivity.this, getString(R.string.verification_code_fail_send));
                        }
                    });
                } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码错误
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            btn_resend.setText(R.string.resend);
//                            btn_resend.setEnabled(true);
//                            ToastUtils.showTopTip(VerifyCodeActivity.this, "验证码校验失败，请稍后再试！");
                            ToastUtils.showTopTip(VerifyCodeActivity.this, getString(R.string.verification_code_error));
                            verify_code_view.setTextColor(R.color.color_FF4E4E);
                        }
                    });
                }

            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.verify_code_main);
        super.onCreate(savedInstanceState);

        String tel = getIntent().getStringExtra(PhoneInputActivity.LOGIN_PHONE);
        country_number = getIntent().getStringExtra(PhoneInputActivity.COUNTRY_NUMBER);
        mTelPhone = tel;
        input_verify_code2 = findViewById(R.id.input_verify_code2);
        input_verify_code2.setText("+"+country_number+tel);

        verify_code_view = findViewById(R.id.verify_code_view);
        verify_code_view.setInputCompleteListener(new VerifyCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                if (!mTelPhone.equals("12312341231") || !mTelPhone.equals("12312341232")
                        || !mTelPhone.equals("12312341233") || !mTelPhone.equals("12312341234") || !mTelPhone.equals("15262840973")) {
                    SMSSDK.submitVerificationCode(country_number, mTelPhone, verify_code_view.getEditContent());
                }
            }

            @Override
            public void invalidContent() {

            }

            @Override
            public void inputTest() {
                if (mTelPhone.equals("12312341231") || mTelPhone.equals("12312341232")
                        || mTelPhone.equals("12312341233") || mTelPhone.equals("12312341234")|| mTelPhone.equals("15262840973")) {
                    userAuthenticate(VerifyCodeActivity.this, mTelPhone, "123456");
                }
            }
        });
        btn_resend = findViewById(R.id.btn_resend);
        btn_resend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                send(mTelPhone);
            }
        });
        if (!mTelPhone.equals("12312341231") && !mTelPhone.equals("12312341232")
                && !mTelPhone.equals("12312341233") && !mTelPhone.equals("12312341234")) {
            SMSSDK.registerEventHandler(eh);
        }
        send(mTelPhone);
    }

    private void userAuthenticate(Context context, String telPhone, String password) {

        LoadingView.createLoadingViewAndShow(VerifyCodeActivity.this, R.style.CustomDialog, context.getString(R.string.logining_wait));
        String platformInfo = "Android-" + LoginActivity.getDeviceBrand() + "-" + LoginActivity.getSystemModel() + "-"
                + LoginActivity.getSystemVersion() + "-" + LoginActivity.getVersionName(this);
        String language = getSharedPreferences("app_language",Context.MODE_PRIVATE).getString("lauType",Locale.getDefault().getLanguage());
        Observable<BaseEntity<AuthenticateInfo>> observable = RetrofitFactory.getInstance().userAuthenticate("111", telPhone, password, platformInfo,language);
        final String tel = telPhone;
        BaseObserver mBaseObserver = new BaseObserver<AuthenticateInfo>(context) {
            @Override
            protected void onHandleError(int code) {
                super.onHandleError(code);
                Log.d(TAG, "onHandleError code = " + code);
            }

            @Override
            protected void onHandleSuccess(AuthenticateInfo userInfo) {
                // 保存用户信息等操作
                Log.d(TAG, "onHandleSuccess userInfo = " + userInfo);


                RoomAiWriterDatabase db = RoomAiWriterDatabase.getInstance(VerifyCodeActivity.this);
                UserEntity user = new UserEntity();
                user.setUid(userInfo.getuId());
                user.setAccessToken(userInfo.getAccessToken());
                user.setExpireTime(userInfo.getExpireTime());
                user.setRefreshToken(userInfo.getRefreshToken());
                user.setPhoneNum(tel);
                db.userDao().clearTable();
                db.userDao().insert(user);

                Intent intent = new Intent(VerifyCodeActivity.this, BottomBarActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                NoteLabelLogic.getNoteLabel(VerifyCodeActivity.this, null);
            }
        };
        observable.compose(RxSchedulers.compose()).subscribe(mBaseObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //用完回调要注销掉，否则可能会出现内存泄露
        SMSSDK.unregisterEventHandler(eh);
    }

    private void send(String tel) {
        //注册回调监听，放到发送和验证前注册，注意这里是子线程需要传到主线程中去操作后续提示

// 请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
        SMSSDK.getVerificationCode(country_number, tel);
        btn_resend.setEnabled(false);
    }

    private void startCountDownTimer() {
        CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                String s = getString(R.string.resend);
                btn_resend.setText(s + "(" + millisUntilFinished / 1000 + "s)");
            }

            @Override
            public void onFinish() {
                btn_resend.setText(R.string.resend);
                btn_resend.setEnabled(true);
            }
        }.start();
    }


    public void sendCode(String country, String phone) {
        // 注册一个事件回调，用于处理发送验证码操作的结果
        SMSSDK.registerEventHandler(new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    System.out.println("--------回调---");
                    // TODO 处理成功得到验证码的结果
                    // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        System.out.println("--------event---" + event + "--------result*" + result);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                System.out.println("----------");
                            }
                        });
                    }
                } else {
                    // TODO 处理错误的结果
                    System.out.println("-------------------------发送失败" + result + data);
                    //				((Throwable) data).printStackTrace();
//				Toast.makeText(MainActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
//					Toast.makeText(MainActivity.this, "123", Toast.LENGTH_SHORT).show();
                    int status = 0;
                    try {
                        ((Throwable) data).printStackTrace();
                        Throwable throwable = (Throwable) data;

                        JSONObject object = new JSONObject(throwable.getMessage());
                        String des = object.optString("detail");
                        status = object.optInt("status");
                        if (!TextUtils.isEmpty(des)) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    System.out.println("----------");
                                }
                            });
                            return;
                        }
                    } catch (Exception e) {
                    }
                }

            }
        });
    }
}
